#include "drv_key.h"

#include "flexible_button.h"

typedef enum
{
    USER_BUTTON_0 = 0,
    USER_BUTTON_1,
    USER_BUTTON_2,
    USER_BUTTON_MAX
} user_button_t;

static flex_button_t user_button[USER_BUTTON_MAX];

uint8_t key1_click_flag, key2_click_flag, key3_click_flag;

void key_gpio_init(void)
{
    gpio_init_type gpio_initstruct = {0};
    
    crm_periph_clock_enable(CRM_GPIOA_PERIPH_CLOCK, TRUE);
    gpio_default_para_init(&gpio_initstruct);
    gpio_initstruct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER;
    gpio_initstruct.gpio_mode = GPIO_MODE_INPUT;
    gpio_initstruct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL;
    gpio_initstruct.gpio_pins = GPIO_PINS_10 | GPIO_PINS_11 | GPIO_PINS_12;
    gpio_initstruct.gpio_pull = GPIO_PULL_UP;
    gpio_init(GPIOA, &gpio_initstruct);
}

static uint8_t common_btn_read(void *arg)
{
    uint8_t value = 0;
    flex_button_t *btn = (flex_button_t *)arg;

    switch (btn->id)
    {
    case USER_BUTTON_0:
        value = KEY1_READ();
        break;
    case USER_BUTTON_1:
        value = KEY2_READ();
        break;
    case USER_BUTTON_2:
        value = KEY3_READ();
        break;
    default:
        break;
    }

    return value;
}

static void common_btn_evt_cb(void *arg)
{
    flex_button_t *btn = (flex_button_t *)arg;

//    rt_kprintf("id: [%d - %s]  event: [%d - %30s]  repeat: %d\n", 
//        btn->id, enum_btn_id_string[btn->id],
//        btn->event, enum_event_string[btn->event],
//        btn->click_cnt);
    
    if(btn->event == FLEX_BTN_PRESS_CLICK)
    {
        switch(btn->id)
        {
            case 0:
                key1_click_flag = 1;
                break;
            case 1:
                key2_click_flag = 1;
                break;
            case 2:
                key3_click_flag = 1;
                break;
            default:
                break;
        }
    }
}

void key_scan_init(void)
{
    for (uint8_t i = 0; i < USER_BUTTON_MAX; i ++)
    {
        user_button[i].id = i;
        user_button[i].usr_button_read = common_btn_read;
        user_button[i].cb = common_btn_evt_cb;
        user_button[i].pressed_logic_level = 0;
        user_button[i].short_press_start_tick = FLEX_MS_TO_SCAN_CNT(1500);
        user_button[i].long_press_start_tick = FLEX_MS_TO_SCAN_CNT(3000);
        user_button[i].long_hold_start_tick = FLEX_MS_TO_SCAN_CNT(4500);

        flex_button_register(&user_button[i]);
    }
}
